﻿using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Colors;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using DotNetARX;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using YZQ_DotNetArx.CAD;
using static DotNetARX.HatchTools;

namespace YZQ_DotNetArx.Test
{
    public static class HatchColor
    {
        [CommandMethod("TC")]
        public static void TC()
        {
            Database db = Application.DocumentManager.MdiActiveDocument.Database;
            //读取规划用地填充层名称
            DocumentLock documentLock = Env.Document.LockDocument();
            PromptOpenFileOptions pfo = new PromptOpenFileOptions("打开数据文件对话框");
            pfo.Filter = "txt file(*.txt)|*.txt|All File(*.*)|*.*";
            PromptFileNameResult pfr = Env.Editor.GetFileNameForOpen(pfo);
            //键是线的图层名，值是填充的图层名称
            Dictionary<string, string> layerNames = new Dictionary<string, string>();
            if (pfr.Status == PromptStatus.OK)
            {
                string strName = pfr.StringResult;
                if (strName == "") return;
                string[] contens = File.ReadAllLines(strName);
                for (int i = 0; i < contens.Count(); i++)
                {
                    layerNames.Add(contens[i].Split('_')[1], contens[i]);
                }
            }
            //用于记录创建失败的图层
            HashSet<string> errorLayers = new HashSet<string>();
            //用于记录被填充实体的个数
            int hatchNum = 0;
            //用于记录封闭实体的数量
            int closedNum = 0;
            //创建进度条
            ProgressMeter pm = new ProgressMeter();         
            PromptSelectionResult psr = Env.Editor.SelectAll();
            if (psr.Status != PromptStatus.OK)
                return;
            if (psr.Value.GetObjectIds() == null)
                return;
            pm.SetLimit(psr.Value.Count);
            pm.Start("正在创建图层并填充实体");
            using (Transaction trans = Env.Database.TransactionManager.StartTransaction())
            {
                foreach (ObjectId id in psr.Value.GetObjectIds())
                {
                    Polyline pl = trans.GetObject(id, OpenMode.ForRead) as Polyline;
                    if (pl == null) continue;
                    if (pl.Closed == false) continue;
                    closedNum++;
                    LayerTableRecord ltr = pl.LayerId.GetObject(OpenMode.ForRead) as LayerTableRecord;
                    ObjectIdCollection ids = new ObjectIdCollection() { pl.ObjectId };
                    Hatch hatch = new Hatch();
                    hatch.SetDatabaseDefaults();
                    hatch.Color = ltr.Color;
                    ObjectId htLayerId = new ObjectId();
                    try
                    {
                        LayerTableRecord hatltr = new LayerTableRecord();
                        //如果字典中有对应的值则使用对应的填充图层名称
                        if (layerNames.Keys.Contains(ltr.Name))
                        {
                            htLayerId = LayerTools.AddLayer(db, layerNames[ltr.Name]);
                            hatltr =htLayerId.GetObject(OpenMode.ForWrite) as LayerTableRecord;
                            hatltr.Color = ltr.Color;
                            hatch.LayerId = htLayerId;                         
                        }
                        //如果字典中没有对应的值则新建名为A+该图层名的图层
                        else
                        {
                            htLayerId = LayerTools.AddLayer(db, "A" + ltr.Name);
                            hatltr = htLayerId.GetObject(OpenMode.ForWrite) as LayerTableRecord;
                            hatltr.Color=ltr.Color;
                            hatch.LayerId = htLayerId;                      
                            errorLayers.Add(ltr.Name + "未在字典中找到对应值，创建了A" + ltr.Name + "来替代，请检查！");
                        }
                        hatch.CreateHatch(HatchPatternType.PreDefined, HatchPatternName.solid, true);
                        hatch.BackgroundColor = Color.FromRgb(0, 0, 255);
                        hatch.AppendLoop(HatchLoopTypes.Outermost, ids);
                        hatch.EvaluateHatch(true);
                        hatchNum++;
                        //防止进度条显示异常
                        System.Windows.Forms.Application.DoEvents();
                        pm.MeterProgress();
                    }
                    //捕捉未被正确填充的图层或实体并输出未被填充的图层名称
                    catch (System.Exception)
                    {
                        Env.Print1("创建" + ltr.Name + "的填充层时发生了错误");
                    }
                }
                trans.Commit();
            }
            //输出字典中没有对应值的图层
            foreach (var errorLayer in errorLayers)
            {
                Env.Print1(errorLayer);
            }
            Env.Print1($"共选择实体:{psr.Value.Count}个元素,其中封闭实体{closedNum}个，成功填充{hatchNum}个");
            pm.Stop();
            Env.Editor.Regen();
            documentLock.Dispose();
        }
    }
}
